﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Linq;
using System.IO;
using CronCommon;

namespace CronManage
{

    public partial class mailfrm : Form
    {

        public static string connstr;
        private static SqlDataAdapter da;
        public static string testToMailAddress;

        public mailfrm()
        {
            InitializeComponent();
            Dir.CheckDirectory();

            if (!File.Exists("config.xml"))
            {
                MessageBox.Show("配制文件config.xml不存在");
                return;
            }

            connstr = null;
            XDocument xd = XDocument.Load("config.xml");
            foreach (XElement item in xd.Root.Descendants("conndb"))
            {
                connstr = item.Element("connstring").Value;
            }
            foreach (XElement item in xd.Root.Descendants("mail"))
            {
                testToMailAddress = item.Element("TestToMailAddress").Value;
            }
            xd = null;

            if (connstr == null)
            {
                MessageBox.Show("数据库连接字口串没有设写好,请先设写连接");
                return;
            }

        }

        public static SqlConnection GetConnection()
        {
            SqlConnection conn=new SqlConnection(connstr);

            try
            {
                if (conn.State == ConnectionState.Closed) conn.Open();
                return conn;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        private void toolStripButton6_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            new ServerInstall().ShowDialog();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection(connstr);
            SqlCommand cmd = new SqlCommand("select 分+space(1)+时+space(1)+天+space(1)+月+space(1)+周+space(1) [排期],执行命令+space(1)+sn 任务 from crontab where 启用=1", conn);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);

            if (dt.Rows.Count <= 0)
            {
                MessageBox.Show("没有记录");
                return;
            }

            if (File.Exists("crontab"))
            {
                if (!Directory.Exists("bak")) Directory.CreateDirectory("bak");
                File.Move("crontab", $"bak\\crontab-{DateTime.Now.ToString("yyyyMMdd-HHmmssff")}.bak");
            }


            FileStream fs = new FileStream("crontab", FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read);
            StreamWriter m_streamWriter = new StreamWriter(fs, Encoding.GetEncoding("GB2312"));
            //   m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);

            foreach (DataRow dr in dt.Rows)
            {
                m_streamWriter.WriteLine($"{dr[0].ToString()}{Application.StartupPath}\\{dr[1].ToString()}");
            }
            m_streamWriter.Flush();
            m_streamWriter.Close();
            fs.Close();
            MessageBox.Show("刷新完成");

        }

        private void mailfrm_Shown(object sender, EventArgs e)
        {
            refreshdata();

            this.dataGridView1.AutoGenerateColumns = false;
            this.dataGridView1.DataSource = ds.Tables["crontab"];

            this.dataGridView1.Columns["SN"].DataPropertyName = "SN";
            this.dataGridView1.Columns["启用"].DataPropertyName = "启用";
            this.dataGridView1.Columns["排程名称"].DataPropertyName = "排程名称";
            this.dataGridView1.Columns["分"].DataPropertyName = "分";
            this.dataGridView1.Columns["时"].DataPropertyName = "时";
            this.dataGridView1.Columns["天"].DataPropertyName = "天";
            this.dataGridView1.Columns["月"].DataPropertyName = "月";
            this.dataGridView1.Columns["周"].DataPropertyName = "周";

            this.dataGridView1.Columns["执行命令"].DataPropertyName = "执行命令";
            this.dataGridView1.Columns["MailTO"].DataPropertyName = "MailTO";
            this.dataGridView1.Columns["MailCC"].DataPropertyName = "MailCC";
            this.dataGridView1.Columns["MailBCC"].DataPropertyName = "MailBCC";
            this.dataGridView1.Columns["MailSubject"].DataPropertyName = "MailSubject";
            this.dataGridView1.Columns["MailBody"].DataPropertyName = "MailBody";

            this.dataGridView1.Columns["附件文件名"].DataPropertyName = "附件文件名";
            this.dataGridView1.Columns["最后执行时间"].DataPropertyName = "最后执行时间";

            this.dataGridView1.Columns["邮件发送失败重试"].DataPropertyName = "邮件发送失败重试";
            this.dataGridView1.Columns["失败重试次数"].DataPropertyName = "失败重试次数";
            this.dataGridView1.Columns["重试间隔分钟"].DataPropertyName = "重试间隔分钟";

            toolStripStatusLabel2.Text = Services.ServiceStatus(Services.serviceName);

        }

        private void 立即执行_Click(object sender, EventArgs e)
        {
			string filename= $"{Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)}\\{dataGridView1.CurrentRow.Cells["执行命令"].Value.ToString()}";
			System.Diagnostics.Process.Start(filename, dataGridView1.CurrentRow.Cells["SN"].Value.ToString());
        }


        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            ds.Tables["crontab"].Rows[dataGridView1.CurrentRow.Index]["启用"] = true;
            da.Update(ds.Tables["crontab"]);
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            ds.Tables["crontab"].Rows[dataGridView1.CurrentRow.Index]["启用"] = false;
            da.Update(ds.Tables["crontab"]);
        }

        private void toolStripButton7_Click(object sender, EventArgs e)
        {
            if (Services.IsServiceExisted(Services.serviceName))
            {
                Services.ServiceStart(Services.serviceName);
                toolStripStatusLabel2.Text = Services.ServiceStatus(Services.serviceName);
            }
        }

        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            if (Services.IsServiceExisted(Services.serviceName))
            {
                Services.ServiceStop(Services.serviceName);
                toolStripStatusLabel2.Text = Services.ServiceStatus(Services.serviceName);
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            cronjob f1 = new cronjob();
            f1.ShowDialog();
            if (f1.DialogResult == DialogResult.OK)
            {
                refreshdata();
            }
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            cronjob f1 = new cronjob(dataGridView1.CurrentRow.Cells["SN"].Value.ToString());
            f1.ShowDialog();
            if (f1.DialogResult == DialogResult.OK)
            {
                refreshdata();
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            toolStripButton11_Click(sender, e);
        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            DialogResult dialogResult = MessageBox.Show( $"{dataGridView1.CurrentRow.Cells["SN"].Value.ToString()}你真的要删除这个务吗?", "删除任务", MessageBoxButtons.YesNo,MessageBoxIcon.Warning,MessageBoxDefaultButton.Button2); 
            if (dialogResult == DialogResult.No) return;

            string sqlcmd = $"delete crontab where SN='{dataGridView1.CurrentRow.Cells["SN"].Value.ToString()}';delete cronExportFile where SN='{dataGridView1.CurrentRow.Cells["SN"].Value.ToString()}' ";

            SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            SqlCommand deletecmd = new SqlCommand(sqlcmd, conn);
            if (deletecmd.ExecuteNonQuery() > 0)
            {
                refreshdata();
            }
            conn.Close();
        }

        private void refreshdata()
        {
            try
            {
                SqlConnection conn = new SqlConnection(connstr);
                SqlCommand cmd = new SqlCommand(";select * from crontab", conn);
                da = new SqlDataAdapter(cmd);
                new SqlCommandBuilder(da);
                ds.Clear();
                da.Fill(ds, "crontab");
            }
            catch (Exception e)
            {
                MessageBox.Show("数据库连接失败,重新设定数库连接" + e.Message);
                cronconfig f1 = new cronconfig();
                if (f1.ShowDialog() == DialogResult.OK)
                {
                    connstr = f1.retconndbstr;

                    refreshdata();
                    f1.Dispose();
                }
                else
                    Environment.Exit(0);


            }
        }

        private void mailfrm_Load(object sender, EventArgs e)
        {
            //不是慢 是有点闪烁吧 设置双缓冲
            Type type = dataGridView1.GetType();
            System.Reflection.PropertyInfo pi = type.GetProperty("DoubleBuffered",
            System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            pi.SetValue(dataGridView1, true, null);

            if (!File.Exists("config.xml"))
            {
                cronconfig f1 = new cronconfig();
                if (f1.ShowDialog() != DialogResult.OK)
                {
                    Environment.Exit(0);
                }

            }
        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {
            new cronconfig().ShowDialog();
        }

        private void toolStripButton10_Click(object sender, EventArgs e)
        {
            new HistoryRecord().ShowDialog();
        }

        private void toolStripButton11_Click(object sender, EventArgs e)
        {
            CronLogShow f1=  new CronLogShow();
            f1.cronid = dataGridView1.CurrentRow.Cells["SN"].Value.ToString();
            f1.ShowDialog();
        }


        private void 日志查看ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //调用日志
            toolStripButton11_Click(sender,e);
        }


        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            //调用修改
            toolStripButton9_Click(sender, e);
        }

        private void 发送测试邮件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string runCommand = $"{Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)}\\{dataGridView1.CurrentRow.Cells["执行命令"].Value.ToString()}";
            string cronId = $"{dataGridView1.CurrentRow.Cells["SN"].Value.ToString()}";
            System.Diagnostics.Process.Start(runCommand, $" {cronId} -T {testToMailAddress}");
        }
    }

}



